package com.example.utils;

import com.example.exception.CustomException;
import lombok.Data;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;

public class TimeBOrSUtils {

    /**
     * 判断传入的时间序列是否按顺序递增（后面的时间大于或等于前面的时间） * @param times 时间序列 * @return 如果全部按顺序递增返回 true，否则返回 false
     */
    public static boolean compareTime(LocalDateTime... times) {
        if (times == null || times.length < 2) {
            throw new CustomException("400", "时间序列不能为空或长度小于2");
        }
        for (int i = 1; i < times.length; i++) {
            if (times[i] == null || times[i - 1] == null) {
                throw new CustomException("400", "时间序列不能包含null值");
            }
            if (times[i].isBefore(times[i - 1])) {
                return false;
            }
        }
        return true;
    }

    @Data
    public static class TimeDiff {
        public int year;
        public int month;
        public int day;
        public int hour;
        public int minute;
        public int second;
        public String formatted;
        public int whoBigger; // 1 = t1大, 2 = t2大
    }

    /**
     * 计算两个时间差
     *
     * @param t1 时间1
     * @param t2 时间2
     * @return TimeDiff 对象，包含各单位差值、格式化字符串和谁大
     */
    public static TimeDiff diffTimeDetail(LocalDateTime t1, LocalDateTime t2) {
        if (t1 == null || t2 == null) {
            throw new IllegalArgumentException("时间不能为 null");
        }

        TimeDiff diff = new TimeDiff();

        // 判断谁大
        if (t1.isAfter(t2)) {
            diff.whoBigger = 1;
        } else {
            diff.whoBigger = 2;
        }

        // 保证 start <= end
        LocalDateTime start = t1.isBefore(t2) ? t1 : t2;
        LocalDateTime end = t1.isBefore(t2) ? t2 : t1;

        // 计算年月日差
        Period period = Period.between(start.toLocalDate(), end.toLocalDate());
        diff.year = period.getYears();
        diff.month = period.getMonths();
        diff.day = period.getDays();

        // 计算时分秒差
        LocalDateTime temp = start.plusYears(diff.year).plusMonths(diff.month).plusDays(diff.day);
        Duration duration = Duration.between(temp, end);
        diff.hour = (int) duration.toHours();
        diff.minute = (int) (duration.toMinutes() % 60);
        diff.second = (int) (duration.getSeconds() % 60);

        // 构建格式化字符串
        StringBuilder sb = new StringBuilder();
        if (diff.year > 0) sb.append(diff.year).append("年");
        if (diff.month > 0) sb.append(diff.month).append("月");
        if (diff.day > 0) sb.append(diff.day).append("天");
        if (diff.hour > 0) sb.append(diff.hour).append("时");
        if (diff.minute > 0) sb.append(diff.minute).append("分");
        if (diff.second > 0) sb.append(diff.second).append("秒");
        diff.formatted = sb.toString();

        return diff;
    }

}
